<template>
  <div class="container" ref="mainCon">
    <topTitle v-if="!hiddleToolBar" :titleText="titleText"></topTitle>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form
          :inline="true"
          :model="filterField"
          ref="searchConditions"
          label-width="46px"
        >
          <el-form-item label="企业" class="row-padding-bottom keyword">
            <el-input
              v-model="filterField.keyword"
              placeholder="请输入企业或统一社会信用代码"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="月份"
            class="row-padding-bottom"
            v-if="
              abnormalType === '1' ||
              abnormalType === '2' ||
              abnormalType === '3'
            "
          >
            <el-date-picker
              v-model="filterField.startDate"
              value-format="yyyy-MM"
              type="month"
              placeholder="选择月份"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="列入日期"
            class="row-padding-bottom"
            v-if="abnormalType === '4'"
            label-width="80px"
          >
            <el-date-picker
              v-model="filterField.startDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="惩戒开始日期"
            class="row-padding-bottom"
            v-if="abnormalType === '5'"
            label-width="100px"
          >
            <el-date-picker
              v-model="filterField.startDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item>
                        <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button>
                    </el-form-item> -->
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchList"
            class="searchBtn"
          >
            <span>搜索</span>
          </el-button>
          <!-- <el-form-item v-if="isShowAdd">
                        <el-button type="primary" @click="showDialog" class="commonBtn addBtn">添加记录</el-button>
                    </el-form-item>
                    <el-form-item v-if="isShowExport">
                        <el-button type="primary" @click="importTem('importTem')" class="commonBut saveBtn funComBut" icon="icon iconfont icondaochu">
                            <span class="opetareText">导入</span>
                        </el-button>
                        <form id="recordExcelForm" style="display:none">
                            <input type="file" ref="importTem" id="abnormalExcel" name="abnormalExcel" @change="fileChange" />
                        </form>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="downloadTemplate" class="commonBtn downloadBtn">下载导入模板</el-button>
                    </el-form-item> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd || isShowExport">
          <el-button
            v-if="isShowAdd"
            type="primary"
            @click="showDialog"
            icon="icon iconfont icontianjia"
            class="commonBut saveBtn funComBut"
          >
            <span class="opetareText">添加记录</span>
          </el-button>
          <el-button
            v-if="isShowExport"
            type="primary"
            @click="importTem('importTem')"
            class="commonBut saveBtn funComBut"
            style="position: relative; top: 1px"
            icon="icon iconfont icondaoru"
          >
            <span class="opetareText">导入</span>
          </el-button>
          <form id="recordExcelForm" style="display: none">
            <input
              type="file"
              ref="importTem"
              id="abnormalExcel"
              name="abnormalExcel"
              @change="fileChange"
            />
          </form>
          <el-button
            type="primary"
            @click="downloadTemplate"
            class="commonBtn downloadBtn"
            >下载导入模板</el-button
          >
        </div>
        <el-table
          ref="tableBox1"
          @sort-change="sortChange"
          :max-height="tableHeight"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          v-loading="loading"
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="companyName"
            label="企业名称"
            width="230"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                columnName="companyName"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="uscc"
            label="统一社会信用代码"
            align="center"
            :formatter="formatTd"
            width="220"
          ></el-table-column>
          <template
            v-if="
              abnormalType === '1' ||
              abnormalType === '2' ||
              abnormalType === '3'
            "
          >
            <el-table-column
              prop="startDate"
              sortable="custom"
              label="年月"
              align="center"
              width="160"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column label="异常原因" width="230" :formatter="formatTd">
              <template slot-scope="scope">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row.reason"
                  columnName="reason"
                ></copyText>
              </template>
            </el-table-column>
          </template>
          <template v-if="abnormalType === '4'">
            <el-table-column
              prop="startDate"
              sortable="custom"
              label="列入日期"
              align="center"
              width="160"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="organization"
              label="列入机关"
              width="230"
              :formatter="formatTd"
            >
              <template slot-scope="scope">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row.organization"
                  columnName="organization"
                ></copyText>
              </template>
            </el-table-column>
            <el-table-column label="列入原因" width="230" :formatter="formatTd">
              <template slot-scope="scope">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row.reason"
                  columnName="reason"
                ></copyText>
              </template>
            </el-table-column>
          </template>
          <template v-if="abnormalType === '5'">
            <el-table-column
              prop="startDate"
              sortable="custom"
              label="惩戒开始日期"
              width="160"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="endDate"
              sortable="custom"
              label="惩戒结束日期"
              width="160"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              label="联合惩戒原因"
              width="230"
              :formatter="formatTd"
            >
              <template slot-scope="scope">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row.reason"
                  columnName="reason"
                ></copyText>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            prop="statusStr"
            label="状态"
            align="center"
            width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column label="操作" align="left" width="100" fixed="right">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.status === '1' && isShowUpdate"
                placement="top"
                width="200"
                :ref="`popover-${scope.$index}`"
              >
                <p style="line-height: 40px">
                  <i class="el-icon-info" style="color: rgb(255, 153, 0)"></i>
                  您确定撤销该内容吗？
                </p>
                <div style="text-align: right; margin: 0">
                  <el-button
                    size="mini"
                    type="text"
                    @click="
                      scope._self.$refs[`popover-${scope.$index}`].doClose()
                    "
                    >取消</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    @click="revokeRecords(scope)"
                    >确定</el-button
                  >
                </div>
                <el-link slot="reference" type="primary">撤销</el-link>
              </el-popover>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <!-- 添加-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDialog"
      @close="closeDialog('formData')"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="640px"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="150px"
        style="padding-top: 8px"
      >
        <el-form-item label="企业：" prop="companyId">
          <el-select
            v-model="formData.companyId"
            class="mWidth"
            filterable
            placeholder="请选择企业"
            clearable
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码：" prop="uscc">
          <span v-if="formData.companyId">{{ findUscc }}</span>
          <span v-else>选择企业后展示</span>
        </el-form-item>
        <template
          v-if="
            abnormalType === '1' || abnormalType === '2' || abnormalType === '3'
          "
        >
          <el-form-item label="月份：" prop="startDate">
            <el-date-picker
              class="mWidth"
              v-model="formData.startDate"
              value-format="yyyy-MM"
              type="month"
              placeholder="选择月份"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="异常原因：" prop="reason">
            <el-input
              type="textarea"
              class="mWidth"
              :rows="3"
              v-model.trim="formData.reason"
              autocomplete="off"
              clearable
              placeholder="请输入异常原因"
              maxlength="300"
              show-word-limit
            ></el-input>
          </el-form-item>
        </template>
        <template v-if="abnormalType === '4'">
          <el-form-item label="列入日期：" prop="startDate">
            <el-date-picker
              class="mWidth"
              v-model="formData.startDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择列入日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="列入机关："
            prop="organization"
            class="organization"
          >
            <el-input
              class="mWidth"
              v-model.trim="formData.organization"
              placeholder="请输入列入机关"
              clearable
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="列入原因：" prop="reason">
            <el-input
              class="mWidth"
              type="textarea"
              :rows="3"
              v-model.trim="formData.reason"
              autocomplete="off"
              clearable
              placeholder="请输入原因"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
        </template>
        <template v-if="abnormalType === '5'">
          <el-form-item label="惩戒开始日期：" prop="cjstartDate">
            <el-date-picker
              class="mWidth"
              v-model="formData.cjstartDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择开始日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="惩戒结束日期：" prop="endDate">
            <el-date-picker
              class="mWidth"
              v-model="formData.endDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="联合惩戒原因：" prop="reason">
            <el-input
              type="textarea"
              class="mWidth"
              :rows="3"
              v-model.trim="formData.reason"
              autocomplete="off"
              clearable
              placeholder="请输入联合惩戒原因"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog('formData')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="submitRecords('formData')"
          v-sdc
          :loading="isSaveLoading"
          class="save"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import scrollTable from '@/mixin/scrollTable.js'
import common from '../../kits/common'
export default {
  name: 'abnormalTable',
  mixins: [scrollTable],
  props: {
    abnormalType: {
      type: String,
      default: '',
    },
    abnormalTypeDesc: {
      type: String,
      default: '',
    },
    titleText: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      tableList: [],
      requestUrl: 'api-c/companyabnormal/base/list',
      filterField: {
        type: this.abnormalType,
        keyword: '',
        startDate: '',
      },
      pageSize: 20,
      pageNo: 1,
      dialogTitle: '',
      addDialog: false,
      formData: {
        companyId: '',
        startDate: '',
        cjstartDate: '',
        endDate: '',
        organization: '',
        reason: '',
      },
      formRules: {
        companyId: [
          {
            required: true,
            message: '请选择企业',
            trigger: 'change',
          },
        ],
        startDate: [
          {
            required: true,
            message: '请选择',
            trigger: 'change',
          },
        ],
        cjstartDate: [
          {
            required: true,
            message: '请选择开始日期',
            trigger: 'change',
          },
        ],
        endDate: [
          {
            required: true,
            message: '请选择结束日期',
            trigger: 'change',
          },
        ],
        organization: [
          {
            required: true,
            message: '请输入列入机关',
            trigger: 'blur',
          },
        ],
        reason: [
          {
            required: true,
            message: '请输入原因',
            trigger: 'blur',
          },
        ],
      },
      companyOptions: [],
      isSaveLoading: false,
      loading: false,
      isShow: false,
      isShowAdd: false,
      isShowUpdate: false,
      isShowExport: false,
    }
  },
  mounted() {
    switch (this.abnormalType) {
      case '1':
        this.dialogTitle = '添加企业用电异常记录'
        break
      case '2':
        this.dialogTitle = '添加企业用水异常记录'
        break
      case '3':
        this.dialogTitle = '添加企业纳税异常记录'
        break
      case '4':
        this.dialogTitle = '添加企业经营异常记录'
        break
      case '5':
        this.dialogTitle = '添加联合惩戒记录'
        break
      default:
        break
    }
    this.$nextTick(() => {
      this.$refs.pagination.getTableListData()
    })
    if (this.abnormalTypeDesc) {
      this.$store.state.buttonLimitsArr.indexOf(
        `${this.abnormalTypeDesc}:add`
      ) > -1 && (this.isShowAdd = true)
      this.$store.state.buttonLimitsArr.indexOf(
        `${this.abnormalTypeDesc}:update`
      ) > -1 && (this.isShowUpdate = true)
      this.$store.state.buttonLimitsArr.indexOf(
        `${this.abnormalTypeDesc}:export`
      ) > -1 && (this.isShowExport = true)
    }
  },
  computed: {
    findUscc() {
      let uscc = ''
      if (this.formData.companyId) {
        let index = this.companyOptions.findIndex(
          (v) => v.id === this.formData.companyId
        )
        index > -1 && (uscc = this.companyOptions[index].uscc)
      }
      return uscc
    },
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    // 添加
    showDialog() {
      this.addDialog = true
      this.getCompanyList()
    },
    // 下载
    downloadTemplate() {
      this.axios({
        method: 'post',
        url: 'api-c/companyabnormal/base/findurl',
        data: {
          type: this.abnormalType,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 撤销
    revokeRecords(scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      const { id } = scope.row
      this.axios({
        method: 'post',
        url: 'api-c/companyabnormal/base/edit',
        data: {
          id,
          status: '0',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message.success('操作成功')
            this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 企业下拉列表
    getCompanyList(id) {
      this.axios({
        method: 'post',
        url: 'api-c/company/base/companylistbyconditions',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.companyOptions = response.data.result
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 列表
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    searchList() {
      this.pageSize = 20
      this.pageNo = 1
      this.$refs.pagination.getTableListData()
    },
    submitRecords(formName) {
      const url = 'api-c/companyabnormal/base/add'
      let { companyId, startDate, cjstartDate, endDate, organization, reason } =
        this.formData
      if (cjstartDate && endDate && cjstartDate >= endDate) {
        this.$message.error('惩戒开始日期应小于结束日期')
        return
      }
      cjstartDate && (startDate = cjstartDate)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.axios({
            method: 'post',
            url,
            data: {
              companyId,
              startDate,
              endDate,
              organization,
              reason,
              type: this.abnormalType,
            },
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.$message.success('保存成功')
                this.addDialog = false
                this.pageSize = 20
                this.pageNo = 1
                this.$refs.pagination.getTableListData()
              } else {
                this.$message.error(response.data.errorMsg)
              }
              this.isSaveLoading = false
            })
            .catch((error) => {
              if (error.response) {
                this.$message.error(error.response.data)
              }
              this.isSaveLoading = false
            })
        } else {
          return false
        }
      })
    },
    closeDialog(ele) {
      this.$refs[ele].resetFields()
      this.addDialog = false
    },
    importTem(filElem) {
      this.$refs[filElem].dispatchEvent(new MouseEvent('click'))
    },
    // 导入上传备案表
    fileChange() {
      let Filedata = $('#abnormalExcel').val()
      if (!Filedata) {
        return
      }
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: '仅支持上传 excel 表格（xls、xlsx 格式）文件',
          type: 'warning',
        })
        $('#abnormalExcel').val('')
        return
      }
      let _this = this
      let options = {
        url: common.uploadUrl + 'api-c/companyabnormal/base/import',
        type: 'POST',
        dataType: 'json',
        data: {
          type: this.abnormalType,
        },
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('access_token'),
        },
        success: function (data) {
          if (!data.hasError) {
            _this.$message({
              type: 'success',
              message: '导入成功',
              center: true,
            })
            _this.pageSize = 20
            _this.pageNo = 1
            _this.$refs.pagination.getTableListData()
          } else {
            _this.$message({
              type: 'error',
              message: `<div>
                                        <p>导入失败,原因如下:</p>
                                        <p><pre>${data.errorMsg}</pre></p>
                                    </div>`,
              dangerouslyUseHTMLString: true,
              center: true,
            })
          }
        },
        resetForm: true, // 成功提交后，重置表单填写内容
        error: function () {},
      }
      $('#recordExcelForm').ajaxSubmit(options)
    },
  },
}
</script>
<style lang="less" scoped>
.mainCon {
  top: 210px;
  .addBtn {
    width: 76px;
  }
  .downloadBtn {
    width: 92px;
    background: transparent !important;
    border: none !important;
    color: #48a6ff;
    font-weight: bold;
  }
}
.organization {
  /deep/ .el-input--suffix .el-input__inner {
    padding-right: 70px;
  }
}
.keyword {
  /deep/ .el-input--suffix .el-input__inner {
    padding-right: 15px;
  }
}
@import '../../../static/css/filterArea.less';
</style>
